﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;

namespace LiteLauncher.Pages
{
    public partial class SettingPage : Page
    {
        public SettingPage()
        {
            InitializeComponent();
            InitializeEventHandlers();
            LoadCurrentSettings();
        }

        private void InitializeEventHandlers()
        {
            // 实时保存设置
            JavaPathBox.TextChanged += (s, e) => SaveSettings();
            MinMemoryBox.TextChanged += (s, e) => ValidateAndSaveMemory();
            MaxMemoryBox.TextChanged += (s, e) => ValidateAndSaveMemory();

            // 页面离开时强制保存
            this.Unloaded += (s, e) => SaveSettings();
        }

        private void LoadCurrentSettings()
        {
            JavaPathBox.Text = AppSettings.JavaPath;
            MinMemoryBox.Text = AppSettings.MinMemory.ToString();
            MaxMemoryBox.Text = AppSettings.MaxMemory.ToString();
            MinecraftPathBox.Text = AppSettings.MinecraftPath;
        }

        private void SaveSettings()
        {
            try
            {
                // Java路径验证
                if (!string.IsNullOrEmpty(JavaPathBox.Text) &&
                   !File.Exists(JavaPathBox.Text))
                {
                    ShowWarning("Java路径无效，将使用自动检测路径");
                    JavaPathBox.Text = AppSettings.AutoDetectJavaPath();
                }

                AppSettings.JavaPath = JavaPathBox.Text;
                AppSettings.MinecraftPath = MinecraftPathBox.Text;
            }
            catch (Exception ex)
            {
                ShowError($"保存设置失败: {ex.Message}");
            }
        }

        private void ValidateAndSaveMemory()
        {
            if (int.TryParse(MinMemoryBox.Text, out var min) &&
                int.TryParse(MaxMemoryBox.Text, out var max))
            {
                if (min > 0 && max > min)
                {
                    AppSettings.MinMemory = min;
                    AppSettings.MaxMemory = max;
                    return;
                }
            }

            ShowWarning("内存值无效，已重置为默认值");
            AppSettings.ResetMemorySettings();
            LoadCurrentSettings();
        }

        private void BrowseJavaButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                Title = "选择Java运行时",
                Filter = "Java可执行文件|java.exe|所有文件|*.*",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
            };

            if (dialog.ShowDialog() == true)
            {
                JavaPathBox.Text = dialog.FileName;
                SaveSettings();
            }
        }

        private void BrowseMinecraftButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog
            {
                Description = "选择.minecraft文件夹位置",
                ShowNewFolderButton = false
            };

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                MinecraftPathBox.Text = dialog.SelectedPath;
                SaveSettings();
            }
        }

        private void ResetDefaultsButton_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确认恢复默认设置？", "重置设置",
                MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                AppSettings.ResetToDefaults();
                LoadCurrentSettings();
            }
        }

        #region 辅助方法
        private void ShowWarning(string message)
        {
            MessageBox.Show(message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
        }

        private void ShowError(string message)
        {
            MessageBox.Show(message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        #endregion
    }
}